package cn.imnaer.service.rpc.userinfo.impl;

import org.bson.BSONObject;
import org.bson.BasicBSONObject;

import cn.imnaer.common.factory.StringCheckUtils;
import cn.imnaer.service.commom.exception.InviteErrorException;
import cn.imnaer.service.commom.exception.UserAlreadyHasException;
import cn.imnaer.service.persistence.model.User;
import cn.imnaer.service.persistence.model.consts.USER;
import cn.imnaer.service.rest.resquest.model.UserLoginParams;
import cn.imnaer.service.rest.resquest.model.UserRegisterParams;
import cn.imnaer.service.rest.view.model.UserView;
import cn.imnaer.service.rpc.collect.application.CollectComponentRpcApiImpl;
import cn.imnaer.service.rpc.common.CommonRpcApiImpl;
import cn.imnaer.service.rpc.scenic.dao.ScenicContributionDaoImpl;
import cn.imnaer.service.rpc.userinfo.UserComponentRpcApi;
import cn.imnaer.service.rpc.userinfo.dao.UserDaoImpl;
import cn.imnaer.service.rpc.userinfo.process.UserManagerProcess;

public class UserComponentRpcApiImpl extends CommonRpcApiImpl implements UserComponentRpcApi {
	private UserDaoImpl userDaoImpl = UserDaoImpl.getInstance();

	

	@Override
	public User createUser(UserRegisterParams registerParams) throws UserAlreadyHasException {
		// 插入数据
		if (this.findUserByIdentity(registerParams.getEmailOrMobile()) != null) {
			throw new UserAlreadyHasException();
		}
		User user = registerParams.transformUser();
		user = this.userDaoImpl.insert(user,true);
		/**
		 * 给用户创建默认收藏
		 */
		String userId=user.getUserId();
		new CollectComponentRpcApiImpl().createCollectGroup(userId, "手机收藏");
		return user;
	}

	
	@Override
	public User login(UserLoginParams loginParams) {
		BSONObject matcher = new BasicBSONObject();
		String loginNumber = loginParams.getLoginNumber();
		if (loginNumber.contains("@")) {
			matcher.put(USER.email,loginParams.getLoginNumber());
		} else if (StringCheckUtils.isMobileNO(loginNumber)) {
			matcher.put(USER.mobile, loginParams.getLoginNumber());
		} else {
			matcher.put(USER.userId,loginParams.getLoginNumber());
		}
		matcher.put(USER.password, loginParams.getPassword());
		return this.userDaoImpl.findOne(matcher, null);
	}	
	
	
	
	private  User findUserByIdentity(String identityString) {
		UserManagerProcess process = new UserManagerProcess();
		User user = null;
		if (identityString.contains("@")) {
			user = process.getUserInfo(USER.email, identityString);
		} else if (identityString.length() == 11) {
			user = process.getUserInfo(USER.mobile, identityString);
		} else {
			user = process.getUserInfo(USER.userId, identityString);
		}
		return user;
	}


	@Override
	public User getUserInfo(String userId) {
		UserManagerProcess process = new UserManagerProcess();
	    User user=	process.getUserById(userId);
	return  user;
	}
}